package com.ruoyi.common.gscUtil.StudyUtil.MultiDataSourceUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;

/**
 * 3.使用多个数据源
 * 在 Service 或 DAO 层中，可以通过 @Qualifier 注解注入不同的数据源
 */
//@Service
public class MyService3 {

    private final JdbcTemplate jdbcTemplate1;
    private final JdbcTemplate jdbcTemplate2;

    @Autowired
    public MyService3(
            @Qualifier("dataSource1") DataSource dataSource1,
            @Qualifier("dataSource2") DataSource dataSource2) {
        this.jdbcTemplate1 = new JdbcTemplate(dataSource1);
        this.jdbcTemplate2 = new JdbcTemplate(dataSource2);
    }

    public void queryFromDb1() {
        String sql = "SELECT COUNT(*) FROM some_table";
        int count = jdbcTemplate1.queryForObject(sql, Integer.class);
        System.out.println("DB1 Count: " + count);
    }

    public void queryFromDb2() {
        String sql = "SELECT COUNT(*) FROM another_table";
        int count = jdbcTemplate2.queryForObject(sql, Integer.class);
        System.out.println("DB2 Count: " + count);
    }
}